var http = require("http");
var path = require("path");
var express = require("express");
var logger = require("morgan");
var bodyParser = require("body-parser");

var app = express();//创建一个express app

app.set("views",path.resolve(__dirname,"views"));//express视图存放在views内
app.set("view engine" , "ejs");//使用ejs引擎

var entries = [];//创造全局数组存放所有条目
app.locals.entries = entries;//使这个数组可以在所有数组中访问

app.use(logger("dev"));//使用morgan记录每次request请求

app.use(bodyParser.urlencoded({extended:false}));//填充一个req.body变量

app.get("/",function(request,response){
	response.render("index");//主页
});

app.get("/new-entry",function(request,response){
	response.render("new-entry");
});

app.post("/new-entry",function(request,response){
	if(!request.body.title || !request.body.body){
		response.status(400).send("entries must hava a title and a body.");
		return;
	}//如果用户提交的表单没有标题或内容，则返回一个404

	//添加一个新条目到entries
	entries.push({
		title:request.body.title,
		content:request.body.body,
		published:new Date()
	});

	response.redirect("/");//重定向到主页来查看你的新条目
});

//渲染404
app.use(function(request,response){
	response.status(404).render("404");
});

app.listen(3000,function(){
	console.log("app started on port 3000");
});

